<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 18/12/29
 * Time: 上午11:14
 */

/**
 * --------------------------------------------------------------------------
 * 根据IP获取地址信息
 * --------------------------------------------------------------------------
 * @param $ip
 * @param bool|true $city
 * @return mixed
 */
function getAddressByIP($ip , $city = true){
    $conf = config('app.baidu_oauth');
    $uri = "https://api.map.baidu.com/location/ip?ip={$ip}&ak={$conf['ak']}&coor={$conf['coor']}";
    $res = file_get_contents($uri);
    $address = jsonToArr($res);
    if($city) return $address['content']['address_detail']['city'];
    return $address;
}

/**
 * --------------------------------------------------------------------------
 * JSON转数组
 * --------------------------------------------------------------------------
 * @param $data
 * @return mixed
 */
function jsonToArr($data){
    return json_decode($data, true);
}

/**
 * --------------------------------------------------------------------------
 * 对象转数组
 * --------------------------------------------------------------------------
 * @param $data
 * @return mixed
 */
function objectToArr($data){
    return json_decode(json_encode($data), true);
}


function getIp(){
    $ip = null;
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    if(!$ip) return "";
    /*
    处理多层代理的情况
    或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
    */
    if (false !== strpos($ip, ',')){ $ip = reset(explode(',', $ip)); }
    return $ip;
}

function changeArrIndex($arr, $field)
{
    if(!$arr) return [];
    if(!is_array($arr)) $arr = objectToArr($arr);
    $tmp = [];
    foreach($arr as $key => $val)
    {
        $tmp[$val[$field]] = $val;
    }
    return $tmp;
}
